/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.cell;

import it.trick.admin.App;
import it.trick.admin.controller.AddContentsViewController;
import it.trick.admin.controller.ChannelTopController;
import it.trick.admin.controller.DeleteContentsViewController;
import it.trick.admin.controller.EditChapterViewController;
import it.trick.admin.model.ChapterModel;
import it.trick.admin.model.ContentsBaseModel;
import it.trick.admin.model.PageModel;
import java.util.ArrayList;
import java.util.List;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;

/**
 *
 * @author takahara
 */
public class CategoryTreeViewCell extends TreeCell<ContentsBaseModel> {

    private TreeCell treeCell;
    private ContextMenu categoryContextMenu = new ContextMenu();
    private ContextMenu chapterContextMenu = new ContextMenu();



    /**
     * コンストラクタ
     */
    public CategoryTreeViewCell() {

        setTreeCell();

        // コンテキストメニューの初期化
        // カテゴリ専用
        MenuItem addCategoryMenuItem = new MenuItem("カテゴリ追加");
        MenuItem categoryChangeNameMenuItem = new MenuItem("名前変更");

        // キャップター専用
        MenuItem addChapterMenuItem = new MenuItem("キャプター追加");
        MenuItem chapterChangeNameMenuItem = new MenuItem("名前変更");
        MenuItem addPageMenuItem = new MenuItem("ページ追加");
        MenuItem publicMenuItem = new MenuItem("公開/非公開");
        MenuItem openMenuItem = new MenuItem("開く");

        // 共通
        MenuItem changeIndexUpperMenuItem = new MenuItem("上へ ↑");
        MenuItem changeIndexLowerMenuItem = new MenuItem("下へ ↓");
        MenuItem deleteCategoryMenuItem = new MenuItem("削除");


        categoryContextMenu.getItems().addAll(
                addCategoryMenuItem,
                addChapterMenuItem,
                new SeparatorMenuItem(),
                categoryChangeNameMenuItem,
                new SeparatorMenuItem(),
                changeIndexUpperMenuItem,
                changeIndexLowerMenuItem,
                new SeparatorMenuItem(),
                deleteCategoryMenuItem);


        chapterContextMenu.getItems().addAll(
                openMenuItem,
                addPageMenuItem,
                new SeparatorMenuItem(),
                chapterChangeNameMenuItem,
                publicMenuItem,
                new SeparatorMenuItem(),
                changeIndexUpperMenuItem,
                changeIndexLowerMenuItem,
                new SeparatorMenuItem(),
                deleteCategoryMenuItem);


        // ---------------------------------------------------------------------
        // カテゴリ追加イベント
        // ---------------------------------------------------------------------
        addCategoryMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getAddStageController(1), "カテゴリ追加", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // キャプター名前変更イベント
        // ---------------------------------------------------------------------
        categoryChangeNameMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getUpdateStageController(), "名前変更", 500, 150, true);
            }
        });


        // ---------------------------------------------------------------------
        // キャプター追加イベント
        // ---------------------------------------------------------------------
        addChapterMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getAddStageController(2), "キャプター追加", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // キャプター名前変更イベント
        // ---------------------------------------------------------------------
        chapterChangeNameMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getUpdateStageController(), "名前変更", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // ページ追加イベント
        // ---------------------------------------------------------------------
        addPageMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getAddStageController(3), "ページ追加", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // 上移動イベント
        // ---------------------------------------------------------------------
        changeIndexUpperMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                TreeItem<ContentsBaseModel> sel = getTreeItem();
                if (sel != null) {
                    TreeItem<ContentsBaseModel> prarent = sel.getParent();

                    if (prarent != null) {
                        int nIndex = prarent.getChildren().indexOf(sel);
                        if (nIndex > 0) {
                            prarent.getChildren().removeAll(sel);
                            prarent.getChildren().add(nIndex - 1, sel);

                            treeCell.getTreeView().getSelectionModel().select(sel);

                            changeIndex();
                        }
                    }
                }
            }
        });

        // ---------------------------------------------------------------------
        // 下移動イベント
        // ---------------------------------------------------------------------
        changeIndexLowerMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                TreeItem<ContentsBaseModel> sel = getTreeItem();
                if (sel != null) {
                    TreeItem<ContentsBaseModel> prarent = sel.getParent();

                    if (prarent != null) {
                        int nIndex = prarent.getChildren().indexOf(sel);
                        if (nIndex < prarent.getChildren().size() - 1) {
                            prarent.getChildren().removeAll(sel);
                            prarent.getChildren().add(nIndex + 1, sel);

                            treeCell.getTreeView().getSelectionModel().select(sel);

                            changeIndex();
                        }
                    }
                }
            }
        });

        // ---------------------------------------------------------------------
        // 削除イベント
        // ---------------------------------------------------------------------
        deleteCategoryMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getDeleteStageController(), "コンテンツ削除", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // 公開・非公開
        // ---------------------------------------------------------------------
        publicMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                // POST処理
                ChannelTopController.getInstance().publicChapterTask.setup(getItem().getKeyValueString());
                ChannelTopController.getInstance().publicChapterTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                    @Override
                    public void handle(WorkerStateEvent t) {

                        ChapterModel chapterModel = (ChapterModel) getItem();

                        ImageView icon;
                        if (!chapterModel.getPublicFlg()) {
                            icon = new ImageView(new Image("it/trick/admin/resource/images/public_page.png"));
                        } else {
                            icon = new ImageView(new Image("it/trick/admin/resource/images/no_public.png"));
                        }

                        icon.setFitHeight(18.0);
                        icon.setPreserveRatio(true);
                        setGraphic(icon);

                        chapterModel.setPublicFlg(!chapterModel.getPublicFlg());
                    }
                });
                ChannelTopController.getInstance().publicChapterTask.restart();
            }
        });
    }

    private void setTreeCell() {
        treeCell = this;
    }

    /**
     * セル更新
     *
     * @param item
     * @param empty
     */
    @Override
    public void updateItem(final ContentsBaseModel item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            super.setText(item.getName());
            super.setGraphic(getTreeItem().getGraphic());

            // コンテキストメニューの設定
            if (getItem() instanceof ChapterModel) {
                setContextMenu(chapterContextMenu);

                ImageView icon;
                ChapterModel chapterModel = (ChapterModel) getItem();
                if (chapterModel.getPublicFlg()) {
                    icon = new ImageView(new Image("it/trick/admin/resource/images/public_page.png"));
                } else {
                    icon = new ImageView(new Image("it/trick/admin/resource/images/no_public.png"));
                }
                icon.setFitHeight(18.0);
                icon.setPreserveRatio(true);
                setGraphic(icon);

            } else {
                setContextMenu(categoryContextMenu);

                ImageView icon = new ImageView(new Image("it/trick/admin/resource/images/category.png"));
                icon.setFitHeight(18.0);
                icon.setPreserveRatio(true);
                setGraphic(icon);
            }

            // マウスイベント
            this.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent t) {
                    // コンテキストメニュー表示イベント
                    if (t.isControlDown()) {
                        getContextMenu().show(treeCell, t.getScreenX(), t.getScreenY());

                        // キャプター編集イベント（ダブルクリック）
                    } else if (t.getClickCount() == 2 && getItem() instanceof ChapterModel) {

                        ChannelTopController.getInstance().getChapterModelTask.setup(getItem().getKeyValueString());
                        ChannelTopController.getInstance().getChapterModelTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                            @Override
                            public void handle(WorkerStateEvent t) {

                                ChapterModel chapterModel = (ChapterModel)t.getSource().getValue();
                                EditChapterViewController editChapterViewController = new EditChapterViewController(
                                        chapterModel);
                                ChannelTopController.getInstance().mainVBox.getChildren().setAll(editChapterViewController);
                            }
                        });
                        ChannelTopController.getInstance().getChapterModelTask.restart();
                    }
                }
            });
        }
    }

    /**
     * 追加コントロールの取得
     *
     * @param type タイプ（1: category 2: chapter 3:page）
     * @return
     */
    private Pane getAddStageController(final int type) {
        final AddContentsViewController controller = new AddContentsViewController();

        controller.addButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                // 親
                TreeItem<ContentsBaseModel> prarent = getTreeItem().getParent();
                ContentsBaseModel prarentModel = prarent.getValue();

                // -------------------------------------------------------------
                // カテゴリの追加
                // -------------------------------------------------------------
                if (type == 1) {
                    // 送信データ作成
                    ContentsBaseModel baseModel = new ContentsBaseModel();
                    baseModel.setPrarentKeyString(prarentModel.getKeyValueString());
                    baseModel.setName(controller.contentsNameTextField.getText());
                    baseModel.setIndex(prarent.getChildren().size() + 1);

                    // POST処理
                    ChannelTopController.getInstance().addCategoryTask.setup(baseModel);
                    ChannelTopController.getInstance().addCategoryTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {

                            ContentsBaseModel newModel = (ContentsBaseModel) t.getSource().getValue();

                            // ツリービューへの追加
                            if (newModel != null) {
                                TreeItem<ContentsBaseModel> newItem = new TreeItem(newModel);
                                getTreeView().getRoot().getChildren().add(newItem);
                            }
                        }
                    });
                    ChannelTopController.getInstance().addCategoryTask.restart();

                } else if (type == 2) {
                    // -------------------------------------------------------------
                    // キャプター追加
                    // -------------------------------------------------------------
                    ChapterModel baseModel = new ChapterModel();
                    baseModel.setPrarentKeyString(getItem().getKeyValueString());
                    baseModel.setName(controller.contentsNameTextField.getText());
                    baseModel.setIndex(getTreeItem().getChildren().size() + 1);

                    // POST処理
                    ChannelTopController.getInstance().addChapterTask.setup(baseModel);
                    ChannelTopController.getInstance().addChapterTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {

                            ChapterModel newModel = (ChapterModel) t.getSource().getValue();

                            // ツリービューへの追加
                            if (newModel != null) {
                                TreeItem<ContentsBaseModel> newItem = new TreeItem(newModel);
                                getTreeItem().getChildren().add(newItem);
                            }
                        }
                    });
                    ChannelTopController.getInstance().addChapterTask.restart();


                } else if (type == 3) {
                    // -------------------------------------------------------------
                    // ページ追加
                    // -------------------------------------------------------------
                    PageModel baseModel = new PageModel();
                    baseModel.setName(controller.contentsNameTextField.getText());
                    baseModel.setPrarentKeyString(getItem().getKeyValueString());
                    baseModel.setIndex(ChannelTopController.getInstance().pageListView.getItems().size() + 1);

                    // POST処理
                    ChannelTopController.getInstance().addPageTask.setup(baseModel);
                    ChannelTopController.getInstance().addPageTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {

                            PageModel newModel = (PageModel) t.getSource().getValue();

                            // ツリービューへの追加
                            if (newModel != null) {
                                ChannelTopController.getInstance().pageListView.getItems().add(newModel);
                            }
                        }
                    });
                    ChannelTopController.getInstance().addPageTask.restart();
                }

                App.getInstance().closePopStage();
            }
        });


        return controller;
    }

    /**
     * 名前変更
     *
     * @param type
     * @return
     */
    private Pane getUpdateStageController() {
        ContentsBaseModel baseModel = getItem();
        final AddContentsViewController controller = new AddContentsViewController(baseModel.getName());

        controller.addButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                if (getItem() instanceof ChapterModel) {
                    // -------------------------------------------------------------
                    // キャプター名前変更
                    // -------------------------------------------------------------
                    ChapterModel chapterModel = (ChapterModel) getTreeItem().getValue();
                    chapterModel.setName(controller.contentsNameTextField.getText());


                    // POST処理
                    ChannelTopController.getInstance().changeChapterNameTask.setup(chapterModel);
                    ChannelTopController.getInstance().changeChapterNameTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {
                            setText(controller.contentsNameTextField.getText());
                        }
                    });
                    ChannelTopController.getInstance().changeChapterNameTask.restart();


                } else {
                    // -------------------------------------------------------------
                    // カテゴリの名前変更
                    // -------------------------------------------------------------
                    ContentsBaseModel baseModel = getTreeItem().getValue();
                    baseModel.setName(controller.contentsNameTextField.getText());

                    // POST処理
                    ChannelTopController.getInstance().updateCategoryTask.setup(baseModel);
                    ChannelTopController.getInstance().updateCategoryTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {
                            setText(controller.contentsNameTextField.getText());
                        }
                    });
                    ChannelTopController.getInstance().updateCategoryTask.restart();

                }

                App.getInstance().closePopStage();
            }
        });


        return controller;
    }

    /**
     * 順序の更新
     */
    private void changeIndex() {

        TreeItem<ContentsBaseModel> sel = getTreeItem();
        TreeItem<ContentsBaseModel> prarent = sel.getParent();

        List<ContentsBaseModel> modelList = new ArrayList();

        for(TreeItem treeItem: prarent.getChildren()) {
            modelList.add((ContentsBaseModel)treeItem.getValue());
        }

        ChannelTopController.getInstance().changeIndexTask.setup(modelList);
        ChannelTopController.getInstance().changeIndexTask.restart();

    }

    /**
     * コンテンツ削除
     * @return
     */
    private Pane getDeleteStageController() {
        ContentsBaseModel baseModel = getItem();
        DeleteContentsViewController controller = new DeleteContentsViewController(baseModel.getName());

        controller.deleteButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                if (getItem() instanceof ChapterModel) {
                    // POST処理
                    ChannelTopController.getInstance().deleteChapterTask.setup(getItem().getKeyValueString());
                    ChannelTopController.getInstance().deleteChapterTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {
                            getTreeItem().getParent().getChildren().remove(getTreeItem());
                        }
                    });
                    ChannelTopController.getInstance().deleteChapterTask.restart();

                } else {
                    // POST処理
                    ChannelTopController.getInstance().deleteCategoryTask.setup(getItem().getKeyValueString());
                    ChannelTopController.getInstance().deleteCategoryTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                        @Override
                        public void handle(WorkerStateEvent t) {
                            getTreeItem().getParent().getChildren().remove(getTreeItem());
                        }
                    });
                    ChannelTopController.getInstance().deleteCategoryTask.restart();

                }

                App.getInstance().closePopStage();
            }
        });

        return controller;
    }
}
